package com.cg;

import com.alibaba.fastjson.JSON;
import org.apache.kafka.clients.producer.*;
import org.apache.kafka.common.serialization.StringSerializer;

import java.util.Properties;
import java.util.concurrent.ExecutionException;

public class MyKafkaProducer {

    private final static String TOPIC_NAME = "my-replication-topic";

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        Properties properties = new Properties();
        properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "192.168.10.149:9092,192.168.10.149:9093,192.168.10.149:9094");

        //把发送的key从字符串序列化为字节数组
        properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
        //把发送消息value从字符串序列化为字节数组
        properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());

        KafkaProducer<String, String> producer = new KafkaProducer<>(properties);

        User user = new User(1, "che", "重庆");
        ProducerRecord<String, String> producerRecord = new ProducerRecord<String, String>(TOPIC_NAME, user.getUserId().toString(), JSON.toJSONString(user));

        //=====阻塞=======
        RecordMetadata metadata = producer.send(producerRecord).get();
        System.out.println("同步方式发送消息结果：" + "topic-" +metadata.topic() + "|partition-"+ metadata.partition() + "|offset-" +metadata.offset());

        //=====非阻塞=======
//        producer.send(producerRecord, new Callback() {
//            @Override
//            public void onCompletion(RecordMetadata recordMetadata, Exception e) {
//                System.out.println(recordMetadata + "and" + e);
//                if (e != null) {
//                    System.err.println("发送消息失败：" + e.getStackTrace());
//                }
//                if (recordMetadata != null) {
//                    System.out.println("异步方式发送消息结果：" + "topic-" + recordMetadata.topic() + "|partition-" + recordMetadata.partition() + "|offset-" + recordMetadata.offset());
//                }
//            }
//        });

//        Thread.sleep(1000000000);

    }

}
